  function ghand=plotsaj(mat,mode,in)
% =========================================================================
% PLOTSAJ.m 
% PLOTS FOR T X C X P MATRICES depending on mode into: 
% 
% 1) [m n] plots per graph page , with all columns of C in each subplot, 
%          each matrix page, P, per plot 
% 2) [m n] plots per graph page , with each column of C in each subplot, 
%           cutoff per matrix page, P 
% 
% function plotsaj(mat,mode,in);
% 
% 
% Inputs 
% =====
% MAT         matrix (can be unidimensional)
% MODE        1 all columns per matrix page in each subplot 
%             2 each column per matrix page in each subplot  
% IN          structure  
%
%
% Structure in allows for all other options, default values in parenthesis 
% =========================================================================
%
% IN.M          Plots will be divided into panels of m x n plots per page 
%               this defines number of rows ( 2 ) 
%
% IN.N          Plots will be divided into panels of m x n plots per page 
%               this defines number of colums ( 2 ) 
%
% IN.GNAME      File for the graphs, which will be stored as 
%               in.gname_<number>, ( [] in which case plots not saved )  
%   
% IN.OPATH      Output folder where graphs will be stored (  current cd ) 
%
% IN.CNAMES     columns names, cell with dimension C 
%               ( [col1 col2 ....colC] )
%
% IN.PNAMES     pages names, cell with dimension P 
%               ( [page1,...,pageP] ) 
%
% IN.TITLE      string with middle of title. Title will be 
%               [cname  in.title pname ], ( fig ) 
% 
% IN.LEGEND     cell of legends, of dimension C x 1 
%               ( col1, col2 ,..... ) 
% 
% IN.AXFONT      Fonts size for axes ( 7 ) 
% 
% IN.TITFONT     Font size for titles ( 8 )  
% 
% IN.STYLE       Max 6x1 cell with the syle per line 
%                Style, Color, Marker 
% 
% IN.WIDTH       Max 6x1 vector with line widths 
%
% IN.XAXIS       X-axis, [T x 1] ( [1:T] ) 
% 
% IN.YLIM       Limits for the y-axis 
%               Four possibilities. 
%               1) Dimension 2x1 and (1,1) different (2,1) 
%                  then (1,1) Lower Bound ; (2,1) Upper Bound
%
%               2) Dimension 2x1 and (1,1)==(2,1) 
%                  then single number is a percent to add and substract \
%                  from above and below 
%
%               3) Dimension 2 x 2, first column different elements
%                  [   substract from min   Lower Bound; 
%                      add       from max   Upper Bound ]
%                  ( [], axis tight ) 
%
%
%               4) Dimension 2 x 2, first column == elements
%                  [   substract %from min   Lower Bound; 
%                      add same  %from max   Upper Bound ]
%                  ( [], axis tight ) 
%
% IN.YGRID      == 1  Y grid on  ( 0 , Off ) 
%
% IN.XGRID      == 1  X grid on  ( 0 , Off )
% 
% IN.XLABEL        String 
% IN.YLABLE        String 
%
% NOTES: 
% 
% 1) Graph Names 
% ===============
% Name of graphs will depend on the mode used 
% If mode 1 then graphs will be indexed as GNAME (1...TGP) 
% If mode 2 then graphs will be indexed as GNAME PAGENAME (1....TGP) 
% Where TGP is the number of Total Graph Pages = ceil( numplots / (m*n) ) 
% 
% Four options in ylim, in.style and in.width as options 5/16/2005 
%
% Alejandro Justiniano 9/7/2005 
% Corrected multiple plots option when input is single page.
% Full screen graph 
% AJ 6/13/2006 Graphs added an indicator when multiple pages needed
%==========================================================================

%==========================================================================

cucd=cd; 
% =====================================================
%               Matrix dimensions
dim = size( mat ); 
nd  = length( dim ); 
if nd == 2 
    dim = [dim 1]; 
end 

if nd > 3 
    error('Input matrix cannot have more than 3D') 
end 
    
T  = dim(1); 
nc = dim(2); 
np = dim(3); 
    
if nargin < 2 | all( [mode ~= 1 mode~=2] ) == 1 
    error('Must define input MODE as either 1 or 2') 
end

if mode == 1 & dim(2) > 6 
    error('Only allow a maximum of 6 lines per plot') 
end 

% GDIM is the graph dimension 
switch mode 
    case  1 
        
        outdim  = 1; 
        indim   = nc ; 
        gdim    = np ; 
        nlin    = nc ; 
        if np == 1 
            in.m = 1; 
            in.n = 1; 
        end 
        
    case 2 
        outdim = nc ; 
        gdim = nc ; 
        nlin = 1; 
        indim = 1; 
end 

if nargin < 3 
    in.cnames = fnumcell('col ',[1:nc] ); 
else 
    if isstruct( in ) == 0
        error('Input in must be a structure') 
    end 
end
        
% ================================================
% Check fields and assign default values otherwise
% ================================================

% Subplots per graph page 
% ------------------------
[e1,in]=ch_field( in ,'m' );
[e2,in]=ch_field( in ,'n' );
if e1==0 | e2 == 0
    
    in.m = 2  ;
    in.n = ceil( gdim  / 2 ) ;

end 
clear e1 e2; 

ppg = in.m*in.n;

% Save settings 
% --------------
[e,in]=ch_field( in, 'gname' , ' '); 
if e == 0 
    flag_save = 0 ; 
else 
    flag_save = 1; 
    [e,in] = ch_field( in, 'opath', cucd ) ; 
end 

% Column names 
% -------------
[e,in]=ch_field( in, 'cnames' ) ;
if e==0 
    in.cnames = fnumcell('col ',[1:nc] ); 
end 
if length( in.cnames ) ~= nc  
    error('Length of in.cnames does not match number of columns in mat') 
end 

% -------------
% Page names 
% -------------
[e,in]=ch_field( in, 'pnames' ) ;
if e==0 
    
    if np == 1
        in.pnames = {''};
    else
        in.pnames = fnumcell('page ',[1:np] );
    end

else 
    if length( in.pnames ) ~= np  
        error('Length of in.pnames does not match number of pages in mat') 
    end 
end 


[e,in]=ch_field(in,'tight',1);
if e==0 
    flag_tight=0; 
else 
    flag_tight=in.tight;
end 
    


% Plot Line Style indicators 
% ==========================
[e,in]=ch_field( in, 'style' );
if e==0
    style={ 'b-',':r','--k','b-.','r*:','kx--' };
else
    
    style=in.style;
    
    if iscell( style ) == 0 
        error('Input in.style must be a cell')
    end
    
    if length( style ) < nlin
        error('Input in.style must have AT LEAST as many entries as columns in mat')
    end
    
end

% Plot Line Width indicators 
% ==========================
[e,in]=ch_field( in, 'width' );
if e==0
    width =[ 1.0  ; 3 ; 2 ; 2 ; 1.6 ; 1.45 ] ; 
else
    width=in.width;
    if isnumeric( width) == 0 ;
        error('Input in.diwth must be a numeric vector')
    end
    if length( width ) < nlin
        error('Input in.width must have AT LEAST as many entries as columns in mat')
    end
end

[e,in]=ch_field( in, 'title', ' ' );

% Legends always on expect when only one graph per subplot, mode = 2 
[e,in]=ch_field( in, 'legend' );
flag_legend=1; 
if e==0
    if mode == 1
        in.legend = in.cnames;
    else
        flag_legend=0;
    end
end

[e,in]=ch_field(in,'xlabel'); 
if e~=0 
    flag_xlabel=1; 
else 
    flag_xlabel=0; 
end 
    

[e,in]=ch_field(in,'ylabel'); 
if e~=0 
    flag_ylabel=1; 
else 
    flag_ylabel=0; 
end 


[e,in]=ch_field( in, 'axfont',  7 );
[e,in]=ch_field( in, 'xaxis',  [1:T]' );
if e ~= 0 
    in.xaxis=in.xaxis(:); 
    temp=length(in.xaxis(:) ); 
    if temp~=T 
        error('Length of in.xaxis does not match number of rows in mat') 
    end 
    clear temp; 
end 

[e,in]=ch_field( in, 'xoffset' ,0 ) ;
[e,in]=ch_field( in, 'titfont', 8 );
[e,in]=ch_field( in, 'ygrid', 0 );
[e,in]=ch_field( in, 'xgrid', 0 );


% ===========================
% Vector of limist for y-axis 
% ===========================
[e,in]=ch_field( in, 'ylim' );
if e==0
    flag_ylim = 0 ;
else
    mins = min( size(in.ylim) );
    if mins > 2
        error('in.ylim must be of dimension [2 1] or [2 2]' )
    end
    flag_ylim = 1; 
    flag_perc = ( ( in.ylim(1) - in.ylim(2) ) == 0 ) ; 
    caseind = flag_perc*mins + (1-flag_perc)*(mins-1) + mins; 
    clear mins flag_perc    
end
    
% =========================================================    

set(0,'DefaultAxesFontSize',in.axfont);
if in.ygrid ~= 0 
set(0,'DefaultAxesYGrid','on'); 
end 
if in.xgrid ~= 0 
set(0,'DefaultAxesXGrid','on'); 
end 
% ----------------------------------------------
%           Indicators for plots
% ----------------------------------------------
% GDIM      graphs dimension
% PPG       graphs per page
% OUTDIM    Outer loop dimension
%           mode == 1 , == 1
%           mode == 2 , == np
% INDIM     Inner loop dimension
%           mode == 1 , == nc
%           mode == 2 , == 1
%

ipg = 0;        % Indicator graph, subplots
gcount  = 0;    % Graphs Count
pcount  = 0;    % Page   Count

% ============================
%         Begin Plots
% ============================
hh=1;

% =================
% Extract each page
% =================
% aaa={'hh';'jj';'ipg';'gcount';'pcount';'ii'}; 

for hh=1:np;

    % Reset for each page
    if mode == 2
        ipg = 0 ;
        gcount = 0 ;
        pcount = 1;
    end

    jj = 1;
    for jj = 1:outdim

        flag_snow = 0 ; 
        
        gcount = gcount + 1;

        switch mode

            case 1
                xp = squeeze( mat(:,:,hh) ) ;
            case 2
                xp = squeeze( mat(:,jj,hh) );
        end

        if ipg == 0
            figure;
        end

        ipg = ipg + 1;
        subplot(in.m ,in.n , ipg );

        if mode == 1
            hold on;
        end

        ii=1;
        for ii=1:indim;
            
             %bbb=num2cprec( [hh;jj;ipg;gcount;pcount;ii] );
             %printcell( [aaa bbb] ) 
            
            plot( in.xaxis , xp(:,ii) , style{ii} ,'LineWidth', width(ii)  );
        end
        hold off;

        % ==============================================
        %               Axis limits                    %
        % ==============================================
        XLim( [in.xaxis(1)-in.xoffset in.xaxis(end)+in.xoffset] ); 
        
        if flag_ylim == 1
            temp_min = min( min( xp ) );
            temp_max = max( max( xp ) ) ;
            switch caseind

                case 1
                    ylim( [temp_min-in.ylim(1 ) temp_max+in.ylim(2)] );
                case 2
                    ylim( [ temp_min*(1-in.ylim(1)) temp_max*(1+in.ylim(1)) ] );
                case 3
                    temp_min = max( [temp_min-in.ylim(1,1) ; in.ylim(1,2) ] );
                    temp_max = min( [temp_max+in.ylim(2,1) ; in.ylim(2,2) ] );
                    ylim( [temp_min temp_max] );
                case 4
                    temp_min = max( [temp_min - in.ylim(1,1) ; in.ylim(1,2) ] );
                    temp_max = min( [temp_max + in.ylim(2,1) ; in.ylim(2,2) ] );
                    ylim( [temp_min temp_max] );
            end

        end

        % ============================================
        % Titles and decide whether to save or not   %
        % ============================================

        switch mode
            case 1

                title( [in.pnames{hh}, in.title ] ,'FontSize', in.titfont ) ;

                if ipg == 1
                    if flag_legend==1
                        lh =  legend( in.legend ,'Location','Best' ) ;
                        set(lh,'FontSize',in.axfont );
                        legend boxoff
                    end
                end

                if ipg == ppg | gcount == np
                    ipg = 0;
                    pcount = pcount + 1 ;
                    flag_snow = 1       ;
                    
                    if np > ppg 
                        gstr = strcat(in.gname,' g_',num2str( pcount )) ;
                    else
                        gstr = in.gname;
                    end
                    
                end

            case 2

                title( [in.pnames{hh},' ',in.cnames{jj}, in.title ] ,'FontSize', in.titfont ) ;

                
                if ipg == 1
                    if flag_legend==1
                        lh =  legend( in.legend ,'Location','Best' ) ;
                        set(lh,'FontSize',in.axfont );
                        legend boxoff
                    end
                end

                
                if ipg == ppg | gcount == nc
                    ipg = 0;
                    pcount = pcount + 1 ;
                    flag_snow = 1 ;
                    gstr = [in.gname,' ',in.pnames{hh},' g_',num2str( pcount ) ] ;
                end


        end % End Switch
        
        if flag_tight==1 
            axis tight; 
        end 
        
        if flag_xlabel==1 
            xlabel(in.xlabel); 
        end 
        if flag_ylabel==1; 
            ylabel(in.ylabel); 
        end 

        if flag_save == 1;
            if flag_snow == 1

                cd( in.opath );
                saveas(gcf,[char( gstr ),' ',num2str(gcount)],'fig' );
                cd(cucd )
                clear gstr flag_snow

            end
        end

       
    end  % End JJ Outer Loop

end % END HH, Page Loop 
ghand=gcf; 
set(0,'DefaultAxesFontSize','remove');
if in.ygrid ~= 0
    set(0,'DefaultAxesYGrid','remove');
end
if in.xgrid ~= 0
    set(0,'DefaultAxesXGrid','remove');
end
